package com.zzzy.common.util;

import com.zzzy.common.enums.ResultCodeEnum;
import com.zzzy.common.exception.BusinessException;
import org.springframework.cglib.beans.BeanCopier;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * @Description: BeanCopier工具类
 * @Author fc
 * @Date 2021/6/4
 */
public class CglibBeanCopierUtil<T> {
    /**
     * BeanCopier的缓存
     */
    static final ConcurrentHashMap<String, BeanCopier> BEAN_COPIER_CACHE = new ConcurrentHashMap<>();

    /**
     * BeanCopier的copy
     * @param source 源对象
     * @param target 目标对象
     */
    public static <T> void copy(Object source, T target) {
        String key = genKey(source.getClass(), target.getClass());
        BeanCopier beanCopier;
        if (BEAN_COPIER_CACHE.containsKey(key)) {
            beanCopier = BEAN_COPIER_CACHE.get(key);
        } else {
            beanCopier = BeanCopier.create(source.getClass(), target.getClass(), false);
            BEAN_COPIER_CACHE.put(key, beanCopier);
        }
        beanCopier.copy(source, target, null);
    }

    /**
     * @param source 源对象
     * @param targetClass 目标对象class
     * @return
     */
    public static <T> T copy(Object source, Class<T> targetClass) {
        T target;
        try {
            target = targetClass.newInstance();
        } catch (Exception e) {
            throw new BusinessException(ResultCodeEnum.BUSINESS_ERROR);
        }
        copy(source, target);
        return target;
    }
    /**
     * 生成key
     * @param srcClazz 源文件的class
     * @param tgtClazz 目标文件的class
     * @return string
     */
    private static String genKey(Class<?> srcClazz, Class<?> tgtClazz) {
        return srcClazz.getName() + tgtClazz.getName();
    }

    public static <S, T> List<T> convertList(List<S> sourceList, Class<T> targetClass) {
        if (CollectionUtils.isEmpty(sourceList) || Objects.isNull(targetClass)){
            return Collections.emptyList();
        }
        return sourceList.stream().map(s-> copy(s, targetClass)).collect(Collectors.toList());
    }
}
